﻿using System;
using LinFu.AOP.Interfaces;

namespace BrainTechLLC
{
	public class SimpleMethodReplacement : BaseMethodReplacementProvider, IMethodReplacement
	{
		private IMethodReplacementProvider _around;
		private Predicate<IInvocationContext> _predicate;

		public SimpleMethodReplacement(IMethodReplacementProvider around)
		{
			_around = around;
		}

		public SimpleMethodReplacement(IMethodReplacementProvider around, Predicate<IInvocationContext> predicate)
		{
			_around = around;
			_predicate = predicate;
		}

		public Predicate<IInvocationContext> Predicate
		{
			get { return _predicate; }
			set { _predicate = value; }
		}

		public override bool ShouldReplace(IInvocationContext context)
		{
			if (_predicate == null)
				return true;

			// Apply the predicate, if possible
			bool proceed = _predicate(context);

			if (proceed)
				proceed = _around.ShouldReplace(context);

			return proceed;
		}

		protected override IMethodReplacement GetReplacement(IInvocationContext context)
		{
			return _around as IMethodReplacement;
		}

		public override object Invoke(IInvocationContext context)
		{
			return (_around as IMethodReplacement).Invoke(context);
		}
	}
}

